package com.hmaill.item.web;

import com.hmaill.common.dto.PageDTO;
import com.hmaill.item.service.IItemService;
import com.hmaill.pojo.Item;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author lo
 */
@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IItemService itemService;

    /**
     * 分页查询商品
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/list")
    public PageDTO<Item> getList(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                 @RequestParam(value = "size", defaultValue = "5") Integer size) {
        return itemService.getItem(page, size);
    }

    /**
     * 添加商品
     *
     * @param item
     */
    @PostMapping
    public void saveData(@RequestBody Item item) {
        //更新数据库
        itemService.saveData(item);
        // 交换机名称
        String exchangeName = "item.topic";
        // 发送消息
        rabbitTemplate.convertAndSend(exchangeName, "item.upData", item.getId());
    }

    /**
     * 更新商品状态
     * 1,为正常
     * 2.为下架
     *
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void upData(@PathVariable Long id, @PathVariable Integer status) {
        itemService.renew(id, status);
        // 交换机名称
        String exchangeName = "item.topic";
        if (status == 1) {
            // 状态为1 则是添加
            rabbitTemplate.convertAndSend(exchangeName, "item.upData", id);
        } else if (status == 2) {
            //状态为2 则是删除
            rabbitTemplate.convertAndSend(exchangeName, "item.deleteData", id);
        }
    }

    /**
     * 更新商品
     *
     * @param item
     */
    @PutMapping
    public void upDataItem(@RequestBody Item item) {
        itemService.upDataItem(item);
    }

    /**
     * 删除商品
     *
     * @param id
     */
    @DeleteMapping("{id}")
    public void deleteItem(@PathVariable Long id) {
        itemService.deleteItem(id);
/*        // 交换机名称
        String exchangeName = "item.topic";
        // 发送消息
        rabbitTemplate.convertAndSend(exchangeName, "item.deleteData", id);*/
    }

    /**
     * 通过id获取item
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item searchItem(@PathVariable Long id) {
        Item item = itemService.getById(id);
        return item;
    }


}
